package com.ljl.pet.service.impl;

import com.ljl.basic.exception.BusinessException;
import com.ljl.basic.service.IBaiduAiAuditService;
import com.ljl.basic.util.*;
import com.ljl.order.domain.OrderPetAcquisition;
import com.ljl.order.mapper.OrderPetAcquisitionMapper;
import com.ljl.org.domain.Employee;
import com.ljl.org.domain.Shop;
import com.ljl.org.mapper.EmployeeMapper;
import com.ljl.org.mapper.ShopMapper;
import com.ljl.pet.domain.Pet;
import com.ljl.pet.domain.SearchMasterMsg;
import com.ljl.pet.domain.SearchMasterMsgAuditLog;
import com.ljl.pet.dto.MsgDto;
import com.ljl.pet.mapper.PetMapper;
import com.ljl.pet.mapper.SearchMasterMsgAuditLogMapper;
import com.ljl.pet.mapper.SearchMasterMsgMapper;
import com.ljl.pet.query.SearchMasterMsgQuery;
import com.ljl.pet.service.ISearchMasterMsgService;
import com.ljl.basic.service.impl.BaseServiceImpl;
import com.ljl.user.domain.Logininfo;
import com.ljl.user.domain.User;
import com.ljl.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;

    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private PetMapper petMapper;

    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;


    @Override
    public void publish(SearchMasterMsg searchMasterMsg, HttpServletRequest request) {
        // 获取当前登陆用户信息
        Logininfo loginUser = LoginContext.getLoginUser(request);
        // 通过登陆信息获取用户
        User user = userMapper.findByLogininfoId(loginUser.getId());
        // 设置用户id
        searchMasterMsg.setUserId(user.getId());
        searchMasterMsgMapper.save(searchMasterMsg);
        // 2.智能审核
        Boolean textBoo = baiduAiAuditService.textAudit(searchMasterMsg.getName() + searchMasterMsg.getTitle() + searchMasterMsg.getAddress());
        Boolean imgBoo = baiduAiAuditService.imageAudit(searchMasterMsg.getResources());
        if (textBoo && imgBoo) {
            searchMasterMsg.setState(1);
            searchMasterMsg.setNote("审核成功");
            // 获取坐标
            Point point = DistanceUtil.getPoint(searchMasterMsg.getAddress());
            // 获取最近的店铺
            Shop nearestShop = DistanceUtil.getNearestShop(point, shopMapper.findAll());
            // 如果有最近店铺则设置店铺id，并且发送短信
            if (nearestShop != null) {
                searchMasterMsg.setShopId(nearestShop.getId());
                System.out.println("你有新的订单，请及时处理：" + searchMasterMsg.getTitle());
            }
            searchMasterMsgMapper.update(searchMasterMsg);
            // 添加审核日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setState(1);
            log.setNote("审核成功");
            log.setMsgId(searchMasterMsg.getId());
            searchMasterMsgAuditLogMapper.save(log);
        } else {
            // 智能审核失败
            searchMasterMsg.setState(0);
            searchMasterMsg.setNote("审核失败");
            searchMasterMsgMapper.update(searchMasterMsg);
            // 添加审核日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setState(0);
            log.setNote("审核失败，内容违规");
            log.setMsgId(searchMasterMsg.getId());
            searchMasterMsgAuditLogMapper.save(log);
            throw new BusinessException("内容违规");
        }
    }

    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query, HttpServletRequest request) {
        Logininfo logininfo = LoginContext.getLoginUser(request);
        User user = userMapper.findByLogininfoId(logininfo.getId());
        query.setUserId(user.getId());
        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        Logininfo logininfo = LoginContext.getLoginUser(request);
        Employee employee = employeeMapper.findByLogininfoId(logininfo.getId());
        //如果当前管理员是店铺管理员：要设置shopId
        //如果当前管理员是平台管理员：不设置shopId
        if (employee.getShop_id() != null) {//店铺管理员
            query.setShopId(employee.getShop_id());
        }

        return super.queryPage(query);
    }

    @Override
    public void reject(Long id) {
        searchMasterMsgMapper.reject(id);
    }

    @Override
    public void accept(MsgDto msgDto) {
        Long empId = msgDto.getHandler();
        Long msgId = msgDto.getMsgId();
        String note = msgDto.getNote();

        OrderPetAcquisition orderTem = orderPetAcquisitionMapper.findByMsgId(msgId);
        if(orderTem != null){
            throw new BusinessException("你的订单正在处理，请耐心等待!!");
        }

        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.findById(msgId);
        System.out.println(searchMasterMsg);
        Pet pet = searchMasterMsg2pet(searchMasterMsg);
        petMapper.save(pet);
        OrderPetAcquisition order = buildOrder(pet,searchMasterMsg,empId);

        orderPetAcquisitionMapper.save(order);

        System.out.println("你有新的订单服务，请尽快处理");

    }


    private OrderPetAcquisition buildOrder(Pet pet, SearchMasterMsg msg, Long empId) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        String orderSn = CodeGenerateUtils.generateOrderSn(pet.getUserId());
        order.setOrderSn(orderSn);
        order.setDigest(msg.getTitle());
        //两天之后的此刻就是最后收购时间 - 自动通过定时器取消
        long timeTem = System.currentTimeMillis() + 2*24*60*60*1000;
        order.setLastcomfirmtime(new Date(timeTem));
        order.setState(0);//待处理
        order.setPrice(new BigDecimal(msg.getPrice()));
        //paytype//在处理订单时才处理
        order.setPetId(pet.getId());
        order.setUserId(pet.getUserId());
        order.setShopId(pet.getShopId());
        order.setAddress(msg.getAddress());
        order.setEmpId(empId);
        order.setSearchMasterMsgId(msg.getId());
        return order;
    }

    private Pet searchMasterMsg2pet(SearchMasterMsg msg) {
        Pet pet = new Pet();
        pet.setName(msg.getName());
        pet.setCostprice(msg.getPrice().toString());
        pet.setTypeId(msg.getPetType());
        pet.setResources(msg.getResources());
        pet.setShopId(msg.getShopId());
        pet.setUserId(msg.getUserId());
        pet.setSearchMasterMsgId(msg.getId());
        return pet;
    }

}
